package codingflow.com

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.webkit.MimeTypeMap
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import codingflow.com.databinding.ActivityMainBinding
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.squareup.picasso.Picasso

class MainActivity : AppCompatActivity() {

    private val mBind by lazy { ActivityMainBinding.inflate(layoutInflater) }

    private var imageUri: Uri? = null


    val mStoreRef: StorageReference by lazy { FirebaseStorage.getInstance().getReference("uploads") }

    val mDataBaseRef: DatabaseReference by lazy { FirebaseDatabase.getInstance().getReference("uploads") }

    companion object {
        const val PICK_IMAGE_REQUEST = 1
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(mBind.root)
        mBind.choose.setOnClickListener {
            openFileChooser()
        }
        mBind.upload.setOnClickListener {
            uploadFile()
        }
    }

    private fun openFileChooser() {
        startActivityForResult(Intent().apply {
            type = "image/*"
            action = Intent.ACTION_GET_CONTENT
        }, PICK_IMAGE_REQUEST)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.data != null) {
            imageUri = data.data
            Picasso.with(this).load(imageUri).into(mBind.imageView)
        }
    }

    private fun getFileExtension(uri: Uri): String? {
        val cR = contentResolver
        val mime = MimeTypeMap.getSingleton()
        return mime.getExtensionFromMimeType(cR.getType(uri))
    }

    fun uploadFile() {
        if (imageUri != null) {
            var fileReference = mStoreRef.child("${System.currentTimeMillis()}.${getFileExtension(imageUri!!)}")
            fileReference.putFile(imageUri!!).addOnSuccessListener {
                Handler().postDelayed({
                    mBind.progressBar.progress = 0
                }, 5000)
                Toast.makeText(this, "Upload successful", Toast.LENGTH_LONG).show()
                var upload = Upload(mBind.fileName.text.toString(), it.storage.downloadUrl.toString())
                mDataBaseRef.push().key?.let { key ->
                    mDataBaseRef.child(key).setValue(upload)
                }

            }.addOnFailureListener {
                Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
            }.addOnProgressListener {
                var progress = (100.0 * it.bytesTransferred / it.totalByteCount)
                mBind.progressBar.progress = progress.toInt()
            }
        } else {
            Toast.makeText(this, "No file selected", Toast.LENGTH_SHORT).show()
        }
    }
}